package cn.learn.async.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 多线程的锁
 * 读写锁
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年02月05日9:28
 */
public class Cache {

    private static final Map<String, Object> CACHE = new HashMap();

    private static final ReadWriteLock LOCK = new ReentrantReadWriteLock();

    /**
     * 读 共享锁
     */
    public static Object get(String key) {
        LOCK.readLock().lock();
        try {
            return CACHE.get(key);
        } finally {
            LOCK.readLock().unlock();
        }
    }

    /**
     * 写 排他锁
     */
    public static Object put(String key, Object value) {
        LOCK.writeLock().lock();
        try {
            return CACHE.put(key, value);
        } finally {
            LOCK.writeLock().unlock();
        }
    }

    /**
     * 清除数据，排他锁
     */
    public static void clear() {
        LOCK.writeLock().lock();
        try {
            CACHE.clear();
        } finally {
            LOCK.writeLock().unlock();
        }
    }

}
